<template>
  <!-- 书写html结构 只可以有一个div 但是可以嵌套多个div -->
  <div>
    <!-- 根据参数查询 和 添加数据 -->
    <el-row>
      <el-col :span="4">
        <el-input
          v-model="searchForm.loginName"
          placeholder="请输入用户名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="searchForm.phonenumber" 
          placeholder="请输入手机号码"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="searchForm.status"
          placeholder="请选职位状态">
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button
          type="success"
          icon="el-icon-search"
          @click="search"
          v-has="'user:query'"
          >搜索</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-has="'user:add'"
          >添加</el-button
        >
      </el-col>
      <el-col :span="6"></el-col>
    </el-row>
    <!-- 查询的数据指定数据 -->
    <el-table :data="tableData" highlight-current-row style="width: 100%">
      <el-table-column label="用户头像" width="160" height="120">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.avatar"></el-image>
        </template>
      </el-table-column>
      <el-table-column sortable width="100" prop="userName" label="登录账号">
      </el-table-column>
      <el-table-column sortable width="100" prop="loginName" label="用户昵称">
      </el-table-column>
      <el-table-column
        sortable
        width="150"
        prop="phonenumber"
        label="手机号码">
      </el-table-column>
      <el-table-column
        sortable
        width="100"
        prop="sex"
        :formatter="getStatus2"
        label="用户性别">
      </el-table-column>
      <el-table-column
        sortable
        width="100"
        prop="status"
        :formatter="getStatus3"
        label="账号状态">
      </el-table-column>
      <el-table-column
        sortable
        width="100"
        prop="delFlag"
        :formatter="getStatus4"
        label="删除标志">
      </el-table-column>
      <el-table-column
        sortable
        width="99"
        prop="createName"
        label="创建者"></el-table-column>
      <el-table-column
        sortable
        width="150"
        prop="userDate"
        label="创建时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="510">
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-has="'user:update'"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            v-has="'user:delete'"
            type="danger"
            @click="deleteDept(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="success"
            v-has="'user:reset'"
            @click="reset(scope.$index, scope.row)"
            >重置密码</el-button
          >
          <el-button
            size="mini"
            type="success"
            v-has="'user:offlineUser'"
            @click="offlineUser(scope.$index, scope.row)"
            >下线</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="refresh()"
            v-has="'user:flush'"
            >刷新缓存</el-button
          >
          <el-button
            size="mini"
            type="success"
            v-has="'user:giverole'"
            @click="handleRole(scope.$index, scope.row)"
            >授予角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页功能 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3, 6, 12, 24, 120]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--    添加修改弹窗-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          label="登录账号"
          :label-width="formLabelWidth"
          prop="userName">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户昵称"
          :label-width="formLabelWidth"
          prop="loginName">
          <el-input v-model="form.loginName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="url" :label-width="formLabelWidth">
          <!--上传图片  -->
          <el-upload
            class="avatar-uploader"
            action="http://172.16.9.55:16868/upImage/uploadFile"
            name="file1"
            :show-file-list="false"
            :on-success="handleFileSuccess"
            :before-upload="beforeFileUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="formLabelWidth"
          prop="phonenumber">
          <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户性别"
          :label-width="formLabelWidth"
          prop="sex">
          <el-select v-model="form.sex" placeholder="请选用户性别">
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>

        <!--            <el-form-item label="头像路径" :label-width="formLabelWidth" prop="salary">-->
        <!--                <el-input v-model="form.avatar" autocomplete="off"></el-input>-->
        <!--            </el-form-item>-->
        <el-form-item
          label="账号状态"
          :label-width="formLabelWidth"
          prop="status">
          <!--  下拉框 -->
          <el-select v-model="form.status" placeholder="请选择账号状态">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="删除标志"
          :label-width="formLabelWidth"
          prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="请选择删除标志">
            <el-option label="存在" value="0"></el-option>
            <el-option label="删除" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!--授予角色表单-->
    <el-dialog title="角色列表" :visible.sync="dialogVisible" width="30%">
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全选</el-checkbox
      >
      <div style="margin: 15px 0"></div>
      <el-checkbox-group
        v-model="checkedRoles"
        @change="handleCheckedRolesChange">
        <el-checkbox
          v-for="role in roleList" v-if="role.roleId==1"
          :label="role.roleId"
          :key="role.roleId"
         disabled >{{ role.roleName }}
        </el-checkbox>
           <el-checkbox
          v-for="role in roleList" v-if="role.roleId!=1"
          :label="role.roleId"
          :key="role.roleId"
          >{{ role.roleName }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserAndRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<!--书写组件配置项目  相当于写js代码的地方 -->
<script>
//数据 全是json格式
export default {
  //注册属性 父传子 数据传递
  props: {},
  data() {
    //定义数据
    return {
      tableData: [], //表格数据
      currentPage: 1, //页码
      pageSize: 3, //每页显示的数量
      total: 100, //分页总数量
      searchForm: {loginName: "", phonenumber: "",status:""}, //查询携带的参数
      dialogFormVisible: false, //使弹出不显示
      title: "用户添加", //title 默认为 用户添加
      //添加或者更新数据时 携带的参数
      form: {},

      //弹出框的宽度
      formLabelWidth: "120px",

      //角色弹出框设置
      dialogVisible: false, //角色授权表 取消授权  //不显示角色列表对话框
      checkAll: false, //是否全选
      checkedRoles: [], //默认选中的角色
      roleList: [], //有效角色集合
      roleIds: "", //定义所有中的所选角色id集合
      isIndeterminate: true,
      tempUserId: 0, //用户id
      //结束
      imageUrl: "", //上传照片设置
    };
  },
  //初始化数据
  created() {
    this.loadData();
    this.getHaveRole(); //查询所有角色的名称
  },
  //方法书写
  methods: {
    //定义变量_this等于外面的this
    //封装请求数据的方法
    loadData() {
      var _this = this;
      this.$http
        .post("/user/queryPage", {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data:this.searchForm
        })
        .then(function (response) {
          console.log(response);
          //判断是否执行成功
          if (response.data.code == 200) {
            _this.tableData = response.data.data.records;
            _this.total = response.data.data.total;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //实行每页有多少条的方法
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.loadData();
    },
    //实现跳转页的方法
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadData();
    },
    //刷新
    refresh() {
      //原始js重新请求
      location.reload();
    },
    //用户性别 把状态数字,转换成字符
    getStatus2(row, column, cellValue, index) {
      return cellValue == 0 ? "男" : "女";
    },
    //帐号状态 把状态数字,转换成字符
    getStatus3(row, column, cellValue, index) {
      return cellValue == 0 ? "正常" : "停用";
    },
    //删除标志 把状态数字,转换成字符
    getStatus4(row, column, cellValue, index) {
      return cellValue == 0 ? "存在" : "删除";
    },
    //查询方法
    search() {
      this.loadData();
      //搜索时,使页码为1
      this.currentPage = 1;
    },
    //用户更新的方法
    handleEdit(index, row) {
      var _this = this;
      console.log(index, row);
      //使弹出框显示
      this.dialogFormVisible = true;
      //给用户赋值
      this.title = "用户更新";
      //点击查询携带数据
      this.form = row;
      //照片方法
      this.imageUrl = row.avatar;
    },
    //添加数据方法
    handleAdd() {
      //使弹出框显示
      this.dialogFormVisible = true;
      //给用户赋值
      this.title = "用户添加";
      //点击查询携带数据
      this.form = {};
      //照片方法
      this.imageUrl = "";
    },
    //关闭方法
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //删除方法
    deleteDept(row) {
      //确认框提示
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var _this = this;
          this.$http
            .delete("/user/deleteById?id=" + row.userId)
            .then(function (response) {
              console.log(response);
              if (response.data.code == 200) {
                _this.$message({
                  message: "操作成功",
                  type: "success",
                });
                _this.dialogFormVisible = false;
                _this.loadData();
              } else {
                _this.$message("操作失败");
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //实现用户添加或者更新
    addOrUpdate() {
      var uri = "/user/add";
      if (this.title == "用户更新") {
        uri = "/user/update";
      }
      var _this = this;
      this.$http
        .post(uri, this.form)
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            _this.$message({
              message: "操作成功",
              type: "success",
            });
            _this.dialogFormVisible = false;
            _this.loadData();
          } else {
            _this.$message("操作失败");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //重置密码
    reset(index, row) {
      this.$confirm("此操作将重置该账号的密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var _this = this;
          this.$http
            .post("/user/resetting", row)
            .then(function (response) {
              console.log(response);
              if (response.data.code == 200) {
                _this.$message({
                  message: "密码重置成功",
                  type: "success",
                });
                _this.dialogFormVisible = false;
                _this.loadData();
              } else {
                _this.$message("密码重置失败");
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "重置操作已取消",
          });
        });
    },
    //下线
    offlineUser(index, row) {
      this.$confirm("此操作将使该账号下线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var _this = this;
          this.$http
            .post("/user/Offline", row)
            .then(function (response) {
              console.log(response);
              if (response.data.code == 200) {
                _this.$message({
                  message: "该账号以下线",
                  type: "success",
                });
                _this.dialogFormVisible = false;
                _this.loadData();
              } else {
                _this.$message("密码重置成功");
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "下线操作已取消",
          });
        });
    },

    //获取所有角色
    getHaveRole() {
      var _this = this;
      // 使用this.$http向后台发请求
      this.$http
        .post("/role/queryPage", { pageNo: 1, pageSize: 100 })
        .then(function (response) {
          //回调函数
          console.log(response); //前端控制台打印
          //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
          if (response.data.code == 200) {
            _this.roleList = response.data.data.records;
          } else {
            _this.$message.error("执行失败");
          }
        })
        .catch(function (error) {
          //异常处理
          console.log(error);
        });
    },
    //获取当前用户已经拥有的角色
    handleRole(index, row) {
      this.dialogVisible = true; //让对话框显示
      //定义变量
      this.tempUserId = row.userId;
      this.roleIds="";
      var _this = this;
      // 使用axios向后台发请求
      this.$http
        .get("/UserAndRole/queryByUserId?userId=" + row.userId)
        .then(function (response) {
          //回调函数
          console.log(response); //前端控制台打印，response是json对象
          console.log(JSON.stringify(response));
          //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
          if (response.data.code == 200) {
            _this.checkedRoles = [];
            for (var i = 0; i < response.data.data.length; i++) {
              //把查询到的角色添加到集合里
              _this.checkedRoles.push(response.data.data[i].roleId);
              console.log(JSON.stringify(_this.checkedRoles));
               _this.roleIds += response.data.data[i].roleId + ",";
              }
              _this.roleIds = _this.roleIds.substr(0, _this.roleIds.length - 1);
          } else {
            _this.$message.error("执行失败");
          }
        })
        .catch(function (error) {
          //异常处理
          console.log(error);
        });
    },

    //给用户添加角色
    addUserAndRole() {
      var _this = this;
      var roleIdsArrray = this.roleIds.toString().split(",");
      //alert(roleIdsArrray);
      for (var i = 0; i < roleIdsArrray.length; i++) {
        // 使用this.$http向后台发请求
        this.$http
          .post("/UserAndRole/add", {
            userId: this.tempUserId,
            roleId: roleIdsArrray[i],
          }) //请求的参数，json格式
          .then(function (response) {
            //回调函数
            //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
            if (response.data.code == 200) {
              //提示成功
              _this.$message({
                message: "执行成功",
                type: "success",
              });
              //关闭弹框
              _this.dialogVisible = false;
              //重新加载数据
              //_this.loadData();
            } else {
              _this.$message.error("执行失败");
            }
          })
          .catch(function (error) {
            //异常处理
            console.log(error);
          });
      }
    },

    //角色全选
    handleCheckAllChange(val) {
      // alert(val);
      if (val) {
        // alert(JSON.stringify(this.roleList));
        for (var i = 1; i <= this.roleList.length; i++) {
          //alert(this.roleList[i].roleId);
          var tempRI = this.roleList[i].roleId;
          this.checkedRoles.push(tempRI);
          this.roleIds += tempRI + ",";
        }
        //去掉最后一个逗号
        this.roleIds = this.roleIds.substr(0, this.roleIds.length - 1);
        // alert(this.roleIds);
      } else {
        this.checkedRoles = [];
        this.roleIds = "";
      }
    },

    //勾选角色
    handleCheckedRolesChange(value) {
      this.roleIds = value; //把勾选的角色id赋值给roleIds
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roleList.length;
    },
    //处理文件成功后的处理方法
    handleFileSuccess(res, file) {
      alert(JSON.stringify(file))
      alert(JSON.stringify(file.response.data.filePath))
      //回显上传图片
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.avatar = file.response.data.filePath;
    },
    //处理文件成功前的处理方法
    beforeFileUpload(file) {
      const FILE_NAME = file.name;
      if (
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".bmp" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".jpg" &&
        FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".png"
      ) {
        this.$message.warning("仅支持.bmp.jpg.png文件");
        return false;
      }
      // const isJPG = file.type === 'image/jpeg';
      const isLt6M = file.size / 1024 / 1024 < 6;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (isLt6M) {
        this.file = file;
        return true;
      }
      this.$message.warning("请上传不超过6M的文件.");
      return false;
    },
  },
  //声明注解
  components: {},
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
